package com.test.multithread.deadlock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class DeadlockDetector {
    public static void main(String[] args) {
        while (true) {
            ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
            long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
            if (deadlockedThreads != null) {
                System.out.println("检测到死锁");
                ThreadInfo[] infos = threadMXBean.getThreadInfo(deadlockedThreads, true, true);
                for (ThreadInfo info : infos) {
                    System.out.println("死锁线程: " + info.getThreadName());
                    System.out.println("堆栈跟踪:");
                    for (StackTraceElement element : info.getStackTrace()) {
                        System.out.println("    at " + element.toString());
                    }
                }
            } else {
                System.out.println("未检测到死锁");
            }
        }

    }
}